import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns } from '@/components/Pro/';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@/components/Pro/';
import {
  eventControllerAddEventInfo as add,
  eventControllerBatchDelEventInfo as remove,
  eventControllerEditEventInfo as edit,
  eventControllerGetPageList as getList,
} from '@/services/ess/event';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { formatMessage } from '@/utils/globalIntl';
import { message, Modal, Space } from 'antd';
import React, { useRef, useState } from 'react';

import { useIntl, useModel } from 'umi';

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.AddEventReq) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      message.success(formatMessage('global.addSuccessfully'));
      return true;
    }
    return false;
  } catch (error) {
    message.error(formatMessage('global.addFailedTips'));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.EditEventReq) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success(formatMessage('global.editedSuccessfully'));
      return true;
    }
    return false;
  } catch (error) {
    message.error(formatMessage('global.editFailedTips'));
    return false;
  }
};

/**
 * @zh-CN 删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.EditEventReq[]) => {
  if (!selectedRows) return true;
  try {
    const res = await remove(selectedRows.map((row) => row.id));
    if (res.success) {
      message.success(formatMessage('global.delSuccess'));
      return true;
    }
    return false;
  } catch (error) {
    message.error(formatMessage('global.delFailedTips'));
    return false;
  }
};

const TableList: React.FC = () => {
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.EditEventReq>({});
  const [selectedRowsState, setSelectedRows] = useState<API.EditEventReq[]>([]);
  const [disabled, setDisabled] = useState(false);
  const intl = useIntl();

  const deleteRow = (rows: API.EditEventReq[] = selectedRowsState) => {
    if (rows?.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    if (disabled) return;
    setDisabled(true);

    confirm({
      title: intl.formatMessage({ id: 'global.prompt' }),
      content: intl.formatMessage({ id: 'global.delTip' }),
      onOk: async () => {
        const res = await handleRemove(rows);
        if (res) {
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  };

  const startTime = ' 00:00:00';
  const endTime = ' 23:59:59';

  const columns: ProColumns<API.EditEventReq>[] = [
    {
      title: intl.formatMessage({ id: 'alarmManagement.generalProcedure.SN' }),
      hideInSearch: true,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.eventCategory' }),
      dataIndex: 'seniorType',
      request: () => fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_LARGE_CATEGORY),
      valueType: 'select',
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.eventSubcategory' }),
      dataIndex: 'juniorType',
      request: () => fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_SMALL_CATEGORY),
      valueType: 'select',
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.Eventobject' }),
      dataIndex: 'eventObject',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.eventName' }),
      dataIndex: 'eventName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.eventDescription' }),
      dataIndex: 'eventDesc',
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.eventGrade' }),
      dataIndex: 'eventLevel',
      request: () => fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_GRADE),
      valueType: 'select',
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.alarmList.Operator' }),
      dataIndex: 'modifyUser',
      hideInSearch: true,
    },
    {
      title: '变更时间',
      dataIndex: 'modifyTime',
      valueType: 'dateRange',
      width: 150,
      search: {
        transform: (value) => {
          return {
            modifyTimeStart: value[0] + startTime,
            modifyTimeEnd: value[1] + endTime,
          };
        },
      },
      render: (_, record) => record.modifyTime,
    },
    {
      title: intl.formatMessage({ id: 'alarmManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              handleModalOpen(true);
              setCurrentRow(record);
            }}
          >
            {intl.formatMessage({ id: 'alarmManagement.generalProcedure.edit' })}
          </a>
          <a key="delete" className="global-del-color" onClick={() => deleteRow([record])}>
            {intl.formatMessage({ id: 'alarmManagement.generalProcedure.delete' })}
          </a>
        </Space>
      ),
    },
  ];

  const { stationId, tenantId } = useModel('@@initialState')?.initialState || {};
  return (
    <div>
      <ProTable<API.EditEventReq, API.PageParams>
        headerTitle={intl.formatMessage({ id: 'alarmManagement.alarmList.Alarmrule' })}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <HandleBtn
            handleType="add"
            key="add"
            onClick={() => {
              setCurrentRow({});
              handleModalOpen(true);
            }}
          >
            {intl.formatMessage({ id: 'alarmManagement.generalProcedure.new' })}
          </HandleBtn>,
          <HandleBtn
            onClick={() => {
              deleteRow();
            }}
            handleType="delete"
            key="delete"
          >
            {intl.formatMessage({ id: 'alarmManagement.generalProcedure.batchDelete' })}
          </HandleBtn>,
        ]}
        params={{ stationId }}
        request={getList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{ ...currentRow }}
        title={
          currentRow?.id
            ? intl.formatMessage({ id: 'alarmManagement.alarmList.Editevent' })
            : intl.formatMessage({ id: 'alarmManagement.alarmList.Addevent' })
        }
        width="660px"
        colProps={{ md: 12 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.stationId = stationId;
          value.tenantId = tenantId;
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.EditEventReq);
          } else {
            success = await handleAdd(value as API.EditEventReq, intl);
          }
          if (success) {
            handleModalOpen(false);
            actionRef?.current?.reload();
          }
        }}
      >
        <ProFormSelect
          name="seniorType"
          label={intl.formatMessage({ id: 'alarmManagement.alarmList.eventCategory' })}
          request={() => fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_LARGE_CATEGORY)}
          rules={[
            {
              required: true,
              message: '事件大类为必填项',
            },
          ]}
        />
        <ProFormSelect
          name="juniorType"
          label={intl.formatMessage({ id: 'alarmManagement.alarmList.eventSubcategory' })}
          request={() => fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_SMALL_CATEGORY)}
          rules={[
            {
              required: true,
              message: '事件小类为必填项',
            },
          ]}
        />
        <ProFormText
          name="eventObject"
          label={intl.formatMessage({ id: 'alarmManagement.alarmList.Eventobject' })}
          fieldProps={{
            maxLength: 250,
          }}
          rules={[
            {
              required: true,
              message: '事件对象为必填项',
            },
          ]}
        />
        <ProFormSelect
          name="eventLevel"
          label={intl.formatMessage({ id: 'alarmManagement.alarmList.eventGrade' })}
          request={() => fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_GRADE)}
          rules={[
            {
              required: true,
              message: '事件等级为必填项',
            },
          ]}
        />
        <ProFormText
          name="eventName"
          label={intl.formatMessage({ id: 'alarmManagement.alarmList.eventName' })}
          fieldProps={{
            maxLength: 250,
          }}
          rules={[
            {
              required: true,
              message: '事件名称为必填项',
            },
          ]}
        />
        <ProFormTextArea
          colProps={{ md: 24 }}
          label={intl.formatMessage({ id: 'alarmManagement.alarmList.eventDescription' })}
          name="eventDesc"
          fieldProps={{
            maxLength: 100,
          }}
          rules={[
            {
              required: true,
              message: '事件描述为必填项',
            },
          ]}
        />
      </ModalForm>
    </div>
  );
};
export default TableList;
